﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Admin.Appointment;
using BenCaoXuan.Infrastructure.IOC;
using BenCaoXuan.Service.Interface.admin;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BenCaoXuan.Service.Instance.admin
{
    [Inject_]
    public class Appointment_Service : Base_Service, I_Appointment_Service
    {
        private readonly Appointment_IOC _appointment_IOC;
        private readonly Product_IOC _product_IOC;

        public Appointment_Service(Appointment_IOC appointment_IOC,Product_IOC product_IOC)
        {
            _appointment_IOC = appointment_IOC;
            _product_IOC = product_IOC;
        }

        /// <summary>
        /// 取消预约
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Cancel_Appointment(IsBan_Dto dto)
        {
            var data = await _appointment_IOC._appointment_EFCore.GetAll(d => d.AId == dto.id).SingleAsync();
            data.AStatus = -1;
            _appointment_IOC._appointment_EFCore.Update(data);
            var result = await _appointment_IOC._appointment_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }

        /// <summary>
        /// 获取所有预约
        /// </summary>
        /// <param name="fenye_Dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Appointment(Fenye_Dto dto)
        {
            // 获取预约主数据（修正查询条件）
            var mainData = await _appointment_IOC._appointment_EFCore
                .GetAll(out int total, dto.page, dto.limit, false,
                        order => order.APeriod,
                        where => (string.IsNullOrEmpty(dto.key) || where.ACustomerName!.Contains(dto.key)) &&
                                 // 关键修正：仅当 dto.id 有值时才过滤 AProductId
                                 (string.IsNullOrEmpty(dto.id) || where.AProductId == dto.id)
                        )
                .Select(d => new Appointment_Dto
                {
                    id = d.AId,
                    date = d.APeriod.Value.ToString("yyyy-MM-dd"),
                    time = d.ATime,
                    price = d.AMoney,
                    status=d.AStatus,
                    name = d.ACustomerName,
                    phone = d.APhone,
                    allSpecsID = d.AProductId, // 规格ID，逗号分隔
                    packagesId = d.APackageId, // 套餐ID，逗号分隔
                    services = new List<Appointment_Services_Dto>()
                })
                .ToListAsync();

            // 预加载关联数据（不变）
            var allProductPackages = _product_IOC._productPackage_EFCore.GetAll().ToList();
            var allProductSpecs = _product_IOC._productSpecs_EFCore.GetAll().ToList();
            var allProducts = _product_IOC._product_EFCore.GetAll().ToList();

            // 处理服务项（不变）
            foreach (var item in mainData)
            {
                // 1. 处理多套餐
                if (!string.IsNullOrEmpty(item.packagesId))
                {
                    var packageIds = item.packagesId.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (packageIds.Length > 0)
                    {
                        var packages = allProductPackages.Where(p => packageIds.Contains(p.PpId)).ToList();
                        foreach (var package in packages)
                        {
                            item.services.Add(new Appointment_Services_Dto
                            {
                                name = package.PpName,
                                price = Convert.ToInt32(package.PpPrice)
                            });
                        }
                    }
                }

                // 2. 处理多产品规格
                if (!string.IsNullOrEmpty(item.allSpecsID))
                {
                    var specIds = item.allSpecsID.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    if (specIds.Length > 0)
                    {
                        var specs = allProductSpecs.Where(s => specIds.Contains(s.PsId)).ToList();
                        foreach (var spec in specs)
                        {
                            var product = allProducts.FirstOrDefault(p => p.PId == spec.PsProductId);
                            if (product != null)
                            {
                                item.services.Add(new Appointment_Services_Dto
                                {
                                    name = product.PName,
                                    price = Convert.ToInt32(spec.PsPrice)
                                });
                            }
                        }
                    }
                }
            }

            return Get_Result(0, "ok", new { data = mainData, total = total });
        }

        /// <summary>
        /// 获取预约的静态数据
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Appointment_StatisticsData()
        {
            // 初始化统计数据对象
            var data = new AppointmentStatisticsData_Dto
            {
                today = new StatistcsDataDetails_Dto(),
                week = new StatistcsDataDetails_Dto(),
                month = new StatistcsDataDetails_Dto(),
                cancelled = new StatistcsDataDetails_Dto()
            };

            // 获取当前时间（用于时间范围计算）
            var now = DateTime.Now;
            var todayStart = now.Date; // 今日00:00:00
            var todayEnd = todayStart.AddDays(1).AddTicks(-1); // 今日23:59:59.999

            var weekStart = todayStart.AddDays(-(int)todayStart.DayOfWeek); // 本周一00:00:00
            var weekEnd = weekStart.AddDays(7).AddTicks(-1); // 本周日23:59:59.999

            var monthStart = new DateTime(now.Year, now.Month, 1); // 本月1日00:00:00
            var monthEnd = monthStart.AddMonths(1).AddTicks(-1); // 本月最后一天23:59:59.999


            // 1. 今日预约统计
            var todayAppointments = await _appointment_IOC._appointment_EFCore.
                GetAll (a => a.APeriod >= todayStart && a.APeriod <= todayEnd)
                .ToListAsync();
            data.today.count = todayAppointments.Count; // 今日总预约数
                                                        // 今日已完成数
            var todayCompleted = todayAppointments.Count(a => a.AStatus == 1);
            // 计算完成率（避免除以0）
            data.today.completedRate = data.today.count > 0
                ? (int)((double)todayCompleted / data.today.count * 100)
                : 0;


            // 2. 本周预约统计
            var weekAppointments = await _appointment_IOC._appointment_EFCore
                .GetAll(a => a.APeriod >= weekStart && a.APeriod <= weekEnd)
                .ToListAsync();
            data.week.count = weekAppointments.Count; // 本周总预约数
                                                      // 本周已完成数
            var weekCompleted = weekAppointments.Count(a => a.AStatus == 1);
            data.week.completedRate = data.week.count > 0
                ? (int)((double)weekCompleted / data.week.count * 100)
                : 0;


            // 3. 本月预约统计
            var monthAppointments = await _appointment_IOC._appointment_EFCore
                .GetAll(a => a.APeriod >= monthStart && a.APeriod <= monthEnd)
                .ToListAsync();
            data.month.count = monthAppointments.Count; // 本月总预约数
                                                        // 本月已完成数
            var monthCompleted = monthAppointments.Count(a => a.AStatus == 1);
            data.month.completedRate = data.month.count > 0
                ? (int)((double)monthCompleted / data.month.count * 100)
                : 0;


            // 4. 取消预约统计（总取消数占总预约数的比例）
            var totalAppointments =  _appointment_IOC._appointment_EFCore.GetAll().Count(); // 所有预约总数
            var cancelledCount = await _appointment_IOC._appointment_EFCore
                .GetAll()
                .CountAsync(a => a.AStatus == -1); // 取消预约数（假设 status=-1 为已取消）
            data.cancelled.count = cancelledCount;
            // 计算取消占比（总取消数 / 所有预约总数）
            data.cancelled.percentage = totalAppointments > 0
                ? (int)((double)cancelledCount / totalAppointments * 100)
                : 0;

            return Get_Result(0, "ok", data);
           
        }

        /// <summary>
        /// 编辑预约
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Update_Appointment(UpdateAppointment_Dto dto)
        {
            var data =await _appointment_IOC._appointment_EFCore.GetAll(d => d.AId == dto.id).SingleAsync();
            data.APhone = dto.phone;
            data.ATime= dto.time;
            data.APeriod = Convert.ToDateTime(dto.date);
            data.ACustomerName = dto.name;
            _appointment_IOC._appointment_EFCore.Update(data);
            var result = await _appointment_IOC._appointment_EFCore.SaveChangesAsync();
            return Get_Result(result);
        }
    }
}
